import { address_add, address_del, address_edit, address_list } from "@/utils/api";

export default{
    namespaced:true,
    state:{
        addresslist:[],
    },
    mutations:{
        pushed(state,payload){
            var index=state.historylist.findIndex((item)=>{
                return item==payload;
            })
            if(index==-1){
                state.historylist.unshift(payload);
            }else{
                state.historylist.splice(index,1);
                state.historylist.unshift(payload);
            }
            
        },
        del(state,payload){
            state.historylist.splice(payload,1)
        },
        save_address(state,payload){
            state.addresslist.push(payload);
        },
        save_addresslist(state,payload){
            state.addresslist=payload;
        },
        unaddress(state,payload){
            var index=state.addresslist.findIndex((item)=>{
                return item.id==payload.id;
            });
            if(index!=-1){
                state.addresslist.splice(index,1);
            }
        },
        edit_address(state,payload){
            var index=state.addresslist.findIndex((item)=>{
                return item.id==payload.id;
            });
            if(index!=-1){
                state.addresslist.splice(index,1);
                state.addresslist.push(payload);
            }
        }
    },
    actions:{
        request_add_address(store,payload){
            var userid=JSON.parse(localStorage.getItem('userinfo')).id;
            address_add({userid,name:payload.name,phone:payload.phone,address:payload.address}).then((res)=>{
                if(res.data.code==200){
                    store.commit('save_address',payload);
                }
            })
        },
        request_address(store){
            var userid=JSON.parse(localStorage.getItem('userinfo')).id;
            address_list({userid}).then((res)=>{
                if(res.data.code==200){
                    store.commit('save_addresslist',res.data.list);
                }
            })
        },
        request_unaddress(store,payload){
            var userid=JSON.parse(localStorage.getItem('userinfo')).id;
            address_del({userid,addressid:payload.id}).then((res)=>{
                if(res.data.code==200){
                    store.commit('unaddress',payload);
                }
            })
        },
        request_edit_address(store,payload){
            console.log(payload);
            var userid=JSON.parse(localStorage.getItem('userinfo')).id;
            address_edit({userid,name:payload.name,phone:payload.phone,address:payload.address,addressid:payload.addressid}).then((res)=>{
                if(res.data.code==200){
                    store.commit('edit_address',payload);
                }
            })
        },
    },
}